package com.laizt.client.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MacAddressUtil {

    /**
     * 执行单条指令
     * @param cmd 命令
     * @return 执行结果
     * @throws Exception
     */
    public static String command(String cmd) throws Exception{
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        InputStream in = process.getInputStream();
        StringBuilder result = new StringBuilder();
        byte[] data = new byte[256];
        while(in.read(data) != -1){
            String encoding = System.getProperty("sun.jnu.encoding");
            result.append(new String(data,encoding));
        }
        return result.toString();
    }


    /**
     * 根据ip获取mac地址
     * @param ip
     * @return
     */
    public static Map<String,String> getMacAddress(String ip){
         Map<String,String> map  = new HashMap<>();
         map.put("code","0");
         try{
             String result = command("ping "+ip+" -n 3");
             if(result.contains("TTL")){
                 result = command("arp -a "+ip);
             }else{
                 map.put("msg","和ip【"+ip+"】通讯失败,请检查网络或者ip正确性!");
                 return map;
             }
             String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";
             Pattern pattern = Pattern.compile(regExp);
             Matcher matcher = pattern.matcher(result);
             StringBuilder mac = new StringBuilder();
             while (matcher.find()) {
                 String temp = matcher.group();
                 mac.append(temp);
             }
             map.put("msg",mac.toString());
             map.put("code","1");
         }catch (Exception e){
            e.printStackTrace();
             map.put("msg","解析异常,请稍后再试!");
         }
        return map;
    }

    /**
     * @param args
     */
    public static void main(String[] args)  {
        Map<String,String> result = getMacAddress("10.27.9.62");
        System.out.println(result.get("code"));
        System.out.println(result.get("msg"));
    }


}
